/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 言初
 * Date: 2024-05-29
 * Time: 9:49
 */

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class NewTest {
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final byte[] mem = new byte[16]; // 共享内存

    public void writeData(int position, byte data, String threadName) {
        lock.writeLock().lock();
        try {
            mem[position] = data;
            System.out.println(threadName + "-> 数据写入位置 " + position + " : " + data);
        } finally {
            lock.writeLock().unlock();
        }
    }

    public byte readData(int position ,String threadName) {
        lock.readLock().lock();
        try {
            byte data = mem[position];
            System.out.println(threadName + "-> 读取位置 " + position + " 的数据: " + data);
            return data;
        } finally {
            lock.readLock().unlock();
        }
    }

    public static void main(String[] args) {
        NewTest sharedMemory = new NewTest();

        // 创建多个写者线程

        new Thread(() -> {
            System.setProperty("sun.java.command","写者2");
            while (true) {
                byte data = (byte) (Math.random() * 100);
                sharedMemory.writeData((int)(Math.random()*100) % 16, data , "写者2");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();


        new Thread(() -> {
            System.setProperty("sun.java.command","写者1");
            while (true) {
                byte data = (byte) (Math.random() * 100);
                sharedMemory.writeData((int)(Math.random()*100) % 16, data ,"写者1");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        // 创建多个读者线程

        new Thread(() -> {
            System.setProperty("sun.java.command","读者1"); // 设置进程名
            while (true) {
                int position = (int) (Math.random() * 16);
                // System.getProperty("sun.java.command")  得到当前的进程名
                sharedMemory.readData(position,"读者1");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(() -> {
            System.setProperty("sun.java.command","读者2");
            while (true) {
                int position = (int) (Math.random() * 16);
                sharedMemory.readData(position,"读者2");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
